package com.wcz.code.文件读写篇;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.List;

import com.wcz.code.Config;

/**
 * @author 伪尘子
 *
 * 2012-6-27
 */
public class FileHelper {
	
	/**
	 * 写入文件
	 * 
	 * @param filePath 文件路径
	 * @param content 文件内容
	 * @param append 如果为 true，则将字节写入文件末尾处，而不是写入文件开始处
	 * @return 写入是否成功
	 */
	public static boolean writeFile(String filePath, String content, boolean append) {
		try {
			File file = new File(filePath);
			FileOutputStream out = new FileOutputStream(file, append);
			OutputStreamWriter fwout = new OutputStreamWriter(out, Config.CHARSET);
			BufferedWriter bw = new BufferedWriter(fwout);
			FileLock fl = out.getChannel().tryLock();
			if (fl.isValid()) {
				bw.write(content);
				fl.release();
			}
			// 释放资源
			bw.flush();
			fwout.flush();
			out.flush();
			bw.close();
			fwout.close();
			out.close();
			bw = null;
			fwout = null;
			out = null;
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
	
	/**
	 * 读取文件内容到数组中，每行数据为数组的一个元素。
	 * 
	 * @param file 文件
	 * @return 文件内容
	 */
	public static List<String> readFileToList(File file) {
		List<String> lines = new ArrayList<String>();
		if (file != null && file.exists()) {
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			try {
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis, Config.CHARSET);
				br = new BufferedReader(isr);
				String temp = null;
				while ((temp = br.readLine()) != null) {
					lines.add(temp);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (br != null) {
						br.close();
					}
					if (isr != null) {
						isr.close();
					}
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return lines;
	}
}
